#! /bin/sh
#
# Name: rc 
# Date: 2003-06-20 17:27
# Author: MontaVista Software, Inc. <source@mvista.com>
# Copyright: Copyright(C) 1999-2003 MontaVista Software, Inc.
# License: 2003 (c) MontaVista Software, Inc. This file is licensed
#          under the terms of the GNU General Public License version 2.
#          This program is licensed "as is" without any warranty of any
#          kind, whether express or implied.
# 
# Copyright 2002, 2003, 2004 Sony Corporation
# Copyright 2002, 2003, 2004 Matsushita Electric Industrial Co., Ltd.
#
### BEGIN INIT INFO
# Short-Description: start/stop services when the runlevel changes.
# Description: This file is responsible for starting/stopping services when the runlevel changes.
### END INIT INFO 

# Init script information
INIT_NAME=rc
DESC=""

# Individual Daemon information
DAEMON1=
ARGS1=
BASENAME1=${DAEMON1##*/}

# Load init script configuration
[ -f /etc/default/$INIT_NAME ] && . /etc/default/$INIT_NAME

# Source the init script functions
. /etc/init.d/init-functions

#
# Start script or program.
#
startup() {
  #ignore dangling symlink
  [ ! -f "$1" ] && continue

  case "$1" in
	*.sh)
		(
			trap - INT QUIT TSTP
			INIT_NAME=$1
#			set $2
			. $1 $2
			unset INIT_NAME
		)
		;;
	*)
		INIT_NAME=$INIT_NAME $1 $2
		;;
  esac
}

  # Ignore CTRL-C only in this shell, so we can interrupt subprocesses.
  trap ":" INT QUIT TSTP

  # Set onlcr to avoid staircase effect.
  stty onlcr 0>&1

  # Now find out what the current and what the previous runlevel are.

  runlevel=$RUNLEVEL
  # Get first argument. Set new runlevel to this argument.
  [ "$1" != "" ] && runlevel=$1
  if [ "$runlevel" = "" ]
  then
	echo "Usage: $0 <runlevel>" >&2
	exit 1
  fi
  previous=$PREVLEVEL
  [ "$previous" = "" ] && previous=N

  export runlevel previous

  # Is there an rc directory for this new runlevel?
  if [ -d /etc/rc.d/rc$runlevel.d ]
  then
	# First, run the KILL scripts.
	if [ $previous != N ]
	then
		for i in /etc/rc.d/rc$runlevel.d/K[0-9][0-9]*
		do
			# Stop the service.
			startup $i stop
		done
	fi
	# Now run the START scripts for this runlevel.
	for i in /etc/rc.d/rc$runlevel.d/S*
	do
		if [ $previous != N ]
		then
			#
			# Find start script in previous runlevel and
			# stop script in this runlevel.
			#
			suffix=${i#/etc/rc.d/rc$runlevel.d/S[0-9][0-9]}
			stop=/etc/rc.d/rc$runlevel.d/K[0-9][0-9]$suffix
			previous_start=/etc/rc.d/rc$previous.d/S[0-9][0-9]$suffix
			#
			# If there is a start script in the previous level
			# and _no_ stop script in this level, we don't
			# have to re-start the service.
			#
			[ -f $previous_start ] && [ ! -f $stop ] && continue
		fi
		case "$runlevel" in
			0|6)
				startup $i stop
				;;
			*)
				startup $i start
				;;
		esac
	done
  fi

exit 0
